package com.chuanjiabao.wisdom.ui.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;

import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.bean.UpdateFileTeam;
import com.chuanjiabao.wisdom.databinding.ActivityUpdateBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.service.UpdateService;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.dialog.JoinQueueDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;

import java.util.ArrayList;
import java.util.List;

public class UpdateActivity extends BaseActivity {

    ActivityUpdateBinding binding;
    private List<LocalMedia> selectList = new ArrayList<>();
    String homeId, relation = "";

    List<UpdateFileTeam> list = new ArrayList<>();

    //上传头像服务
    private Intent mServiceIntent;
    private UpdateService updateService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            updateService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            updateService = ((UpdateService.MyBinder) service).getService();
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_update);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        mServiceIntent = new Intent(this, UpdateService.class);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(UpdateService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(UpdateService.MESSAGE_ACTION);

        homeId = SpResourceUtil.getHomeId();
        LogUtil.e("家的Id-->" + homeId);
        binding.llModuleFinish.setOnClickListener(this);
        binding.ivModuleCemare.setOnClickListener(this);
        binding.ivModuleText.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llModuleFinish:
                finish();
                break;
            case R.id.ivModuleCemare:
                RxPermissions permissionsSecond = new RxPermissions(UpdateActivity.this);
                permissionsSecond.request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                ).subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) toSelectImgAndVideo();
                    }
                });
                break;
            case R.id.ivModuleText:
                Intent intent = new Intent(UpdateActivity.this, UpdateTextActivity.class);
                intent.putExtra("module_homeId", homeId);
                startActivity(intent);
                break;
            default:
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST && data != null) {
                selectList = PictureSelector.obtainMultipleResult(data);
                Runnable runnable = () -> {
                    for (LocalMedia media : selectList) {
                        SystemClock.sleep(200);
                        updateService.setInfo("home", homeId, SpResourceUtil.getToken(), relation, media.getPath());
                    }
                };
                BHThreadPool.getInstance().executeTask(runnable);

                if (!selectList.isEmpty()) showHintDialog();
            }
        }
    }

    public void showHintDialog() {
        JoinQueueDialog dialog = new JoinQueueDialog(UpdateActivity.this);
        dialog.show();
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onCloseClick() {
                finish();
            }
        });
    }

    public void toSelectImgAndVideo() {
        PictureSelector.create(UpdateActivity.this)
                .openGallery(PictureMimeType.ofAll())
                .theme(R.style.picture_default_style)
                .maxSelectNum(9)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .previewVideo(true)
                .enablePreviewAudio(true)
                .isCamera(false)
                .isZoomAnim(true)
                .imageFormat(PictureMimeType.PNG)
                .setOutputCameraPath("/CustomPath")
                .enableCrop(false)
                .compress(false)
                .synOrAsy(true)
                .glideOverride(160, 160)
                .isGif(true)
                .freeStyleCropEnabled(true)
                .openClickSound(true)
                .withAspectRatio(3, 2)
                .previewEggs(true)
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

}
